import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  Inject,
} from '@nestjs/common';
import { CityWeatherService } from './city-weather.service';
import { CreateCityWeatherDto } from './dto/create-city-weather.dto';
import { UpdateCityWeatherDto } from './dto/update-city-weather.dto';
import pinyin from 'pinyin';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';

@Controller('city-weather')
export class CityWeatherController {
  constructor(private readonly cityWeatherService: CityWeatherService) {}

  @Inject(HttpService)
  private httpService: HttpService;

  @Get('pinyin')
  pinyin(@Query('text') text: string) {
    return pinyin(text, {
      // style: 'normal'
    }).join('');
  }

  @Get('weather/:city')
  async weather(@Param('city') city: string) {
    const cityPinyin = pinyin(city, { style: 'normal' }).join('');
    const key = '575192f6cb0d45b0b4c97ac9949e6085';
    const { data: weatherData } = await firstValueFrom(
      this.httpService.get(
        `https://geoapi.qweather.com/v2/city/lookup?location=${cityPinyin}&key=${key}`,
      ),
    );
    return weatherData;
  }

  @Post()
  create(@Body() createCityWeatherDto: CreateCityWeatherDto) {
    return this.cityWeatherService.create(createCityWeatherDto);
  }

  @Get()
  findAll() {
    return this.cityWeatherService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.cityWeatherService.findOne(+id);
  }

  @Patch(':id')
  update(
    @Param('id') id: string,
    @Body() updateCityWeatherDto: UpdateCityWeatherDto,
  ) {
    return this.cityWeatherService.update(+id, updateCityWeatherDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.cityWeatherService.remove(+id);
  }
}
